<template>
  <!-- 用户管理 -->
  <div class="app-container">
    <div class="app-wrap">
      <search-table ref="table" :table-loading="listLoading" :table-data="dataList" @query="getDataList(true)" @reset="refresh">
        <template v-slot:row></template>
        <template v-slot:actions>
          <el-button type="primary" v-permission="'user.add'" size="mini" icon="el-icon-plus" @click="(isShowDetails = true), (checkedItem = null),getRoleList()">新增</el-button>
          <el-button type="info" size="mini" icon="el-icon-refresh" @click="getDataList">刷新</el-button>
        </template>
        <template>
          <el-table-column align="center" type="index" width="50">
            <template slot-scope="scope">
              <el-radio v-model="scope.row.isChecked" :label="true" @change="handleCurrentChange(scope.row)">{{""}}</el-radio>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="id" label="用户ID" width="100"/>
          <el-table-column align="center" prop="nick_name" label="用户昵称" width="200" show-overflow-tooltip/>
          <el-table-column align="center" prop="user_name" label="登录账号" width="200"/>
          <el-table-column align="center" prop="share_url" label="分享链接" width="120">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" :disabled="!scope.row.share_url" @click.stop="shareUrl(scope.row)">分享链接</el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="role_id" label="用户角色" width="180" >
            <template slot-scope="scope">
              <span>{{ scope.row.role_info }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="login_ip" label="登录IP" width="150" />
          <el-table-column align="center" prop="is_agent" label="是否是渠道" width="150">
            <template slot-scope="scope">
              <el-tag :type="scope.row.is_agent?'success':'info'">{{ scope.row.is_agent?'渠道账号':'普通账号' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="remark" label="备注" width="240" />
          <el-table-column align="center" prop="login_time" label="登录时间" width="180" />
          <el-table-column align="left" fixed="right" prop="operation" label="操作" width="180">
            <template slot-scope="scope">
              <el-tooltip effect="dark" v-permission="'user.edit'" content="编辑" placement="top-start">
                <el-button size="mini" type="warning" @click.stop="editItem(scope.row)"><i class="el-icon-edit-outline" /></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" v-permission="'user.delete'" content="删除" placement="top-start">
                <el-button size="mini" :disabled="userInfo.id!=scope.row.id?false:true" type="danger" icon="el-icon-delete" @click.stop="changeChannel(scope.row)"/>
                <!-- <el-button size="mini" :disabled="userInfo.id!=scope.row.id?false:true" type="danger" icon="el-icon-delete" @click.stop="deleteItem(scope.row)"/> -->
              </el-tooltip>
            </template>
          </el-table-column>
        </template>
        <template v-slot:footer>
          <pagination  :total="currentTotal" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getDataList" />
        </template>
      </search-table>
      <page-details :show="isShowDetails" @onHideDetails="onHideDetails" :data="checkedItem" :roleData="roleDataList"/>
      <el-dialog title="删除渠道账号" :visible.sync="isShowChannelDetails" width="50%" :before-close="onHideDetails">
        <p style="font-size:18px;color:red;font-weight:600;">确定删除该渠道账号并且将玩家信息转入下面渠道?<span style="font-size:15px;">(包括该渠道下角色信息等)</span></p>
        <el-select class="width100" v-model="channelId" placeholder="请选择渠道" filterable style="width:300px">
          <el-option v-show="item.isChecked" :label="item.label" :value="item.value" v-for="(item,index) in channelData" :key="index"></el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button size="medium" @click="onHideDetails(false)">取 消</el-button>
          <el-button size="medium" type="primary" @click="deleteItem">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { throttle } from '@/utils/index'
import {
  userList,
  delUser,
  getUserAgent
} from '@/api/user'
import {
  roleList
} from '@/api/system.js'
import PageDetails from './page-details.vue'
import SearchTable from '@/components/SearchTable'
import { mapActions } from "vuex";
export default {
  name: 'user',
  components: {
    PageDetails,
    SearchTable
  },
  data () {
    return {
      userInfo:this.$store.getters.userInfo,
      roleDataList:[],
      dataList:[],
      channelData: this.$store.state.commonState.channelDataArray,
      checkedItem: null,
      listLoading: false,
      isShowDetails: false,
      isShowChannelDetails:false,
      currentTotal: 0,
      listQuery: {
        page: 1,
        size: 50,
      },
      channelId:'',
    }
  },
  created () {
    // this.getRoleList()
  },
  activated(){
    this.userInfo=this.$store.getters.userInfo
    this.channelData=this.$store.state.commonState.channelDataArray
    this.getRoleList(true)
  },
  methods: {
    ...mapActions({
      'updateChannelData': 'commonState/updateChannelData',
      'updateShowChannelData': 'commonState/updateShowChannelData',
    }),
    // 获取用户列表
    async getDataList (query) {
      let that = this,params=that.listQuery;
      if(query && !query.page){
        params.page=1
        params.size=50
      }
      that.dataList = [];
      that.checkedItem = null;
      that.listLoading = true;
      const response = await userList(params)
      if (response.code==1) {
        if (response.data.list) {
          response.data.list.forEach(item => {
            item.isChecked = false
            item.role_id = Number(item.role_id)
            if (item.login_time) {
              item.login_time = that.$public.localTime(item.login_time)
            } else {
              item.login_time = ''
            }
          })
          that.currentTotal = response.data.total
          that.dataList = response.data.list
        }
      }else{
        that.$message.error(response.msg)
      }
      that.listLoading = false
    },
    // 获取角色列表
    getRoleList (show) {
      let that = this;
      that.roleDataList = [];
      roleList({
        page: 1,
        size: 500,
      }).then(function (res) {
        if (res.data.list) {
          that.roleDataList = res.data.list
          if(show){
            that.getDataList()
          }
        }
      }).catch((error) => {
        that.$message.error(error.msg)
      })
    },
    // 编辑
    editItem (row) {
      let that = this;
      that.isShowDetails = true
      that.checkedItem = row
      that.handleCurrentChange(row)
    },
    // 删除
    changeChannel(row){
      this.handleCurrentChange(row)
      this.channelId=''
      if(row.is_agent){
        this.isShowChannelDetails=true
        this.channelData.map(item=>{
          item.isChecked = true
          if(item.value==row.id){
            item.isChecked = false
          }
        })
      }else{
        this.deleteItem()
      }
    },
    deleteItem () {
      // let that = this;
      let that = this,row=that.checkedItem;
      if(row.is_agent){
        if(!that.channelId){
          return that.$message.error('请选择渠道')
        }
      }
      that.$confirm(`是否删除【${row.nick_name}】用户`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        delUser({
          id: row.id,
          new_agent_id:that.channelId?that.channelId:0
        }).then(function (res) {
          that.$message({
            type: 'success',
            message: '删除成功!'
          });
          that.onHideDetails(true)
        })
      }).catch(() => { });
    },
    // 分享链接
    shareUrl(row) {
      window.open(row.share_url)
    },
    // 角色展示
    roleLabel(cellValue){
      if(cellValue!=31){
        return (this.roleDataList.find((item) => item.id == cellValue).role_name || "-");
      }
    },
    // 选择表格数据
    handleCurrentChange (val) {
      this.checkedItem = val;
      this.dataList.map(item => {
        if (item.id === val.id) {
          item.isChecked = true
        } else {
          item.isChecked = false
        }
      })
    },
    // 隐藏详情
    onHideDetails (show) {
      this.channelData=[]
      this.isShowDetails = false
      this.isShowChannelDetails = false
      this.updateChannelData(true)
      this.updateShowChannelData(true)
      if (show) {
        this.getDataList(true)
        getUserAgent({}).then(res=>{
          res.data?.forEach((s) => {
            const item = {
              value: s?.id,
              label: s?.nick_name,
            };
            this.channelData.push(item)
          });
        })
      }
    },
    // 刷新
    refresh: throttle(function () {
      this.listQuery = {
        page: 1,
        size: 50,
      }
      this.getDataList();
    }, 2000),
  }
}
</script>

<style lang="scss" scoped>
</style>
